package excelrept

import (
	"errors"
	"fmt"
	"strings"

	"github.com/extrame/xls"
)

//XlsHelper Xls读写器
type XlsHelper struct {
	workBook *xls.WorkBook
}

//NewXlsHelper 创建Xls读写器
func NewXlsHelper(path string) (*XlsHelper, error) {
	book, err := xls.Open(path, "utf-8")
	if err != nil {
		return nil, err
	}
	return &XlsHelper{
		workBook: book,
	}, nil
}

//ReadeCells 从指定的sheet和范围中读取数据
func (x *XlsHelper) ReadeCells(sheet string, rg string) (cells map[string]string, err error) {
	if rg == "" {
		return
	}
	bs, err := x.getSheet(sheet)
	if err != nil {
		return nil, err
	}
	aa := strings.Split(rg, ":")
	if len(aa) != 2 {
		err = fmt.Errorf("非法的单元格表达式%s", rg)
		return
	}
	var scol, srow, ecol, erow int
	scol, srow, err = parseAxis(aa[0])
	if err != nil {
		return
	}
	if scol > ecol {
		err = fmt.Errorf("非法的单元格范围表达式%s", rg)
		return
	}
	if srow > erow {
		err = fmt.Errorf("非法的单元格范围表达式%s", rg)
		return
	}
	ecol, erow, err = parseAxis(aa[1])
	if err != nil {
		return
	}
	var axis string
	cells = make(map[string]string)
	for i := scol; i <= ecol; i++ {
		for j := srow; j <= erow; j++ {
			val := bs.Row(i).Col(j)
			cells[axis] = val
		}
	}
	return
}

//WriteCells 向指定的sheet写入值
func (x *XlsHelper) WriteCells(sheet string, cells map[string]string) error {
	return errors.New("不支持写数据")
}

func (x *XlsHelper) getSheet(sheetName string) (*xls.WorkSheet, error) {
	count := x.workBook.NumSheets()
	for i := 0; i < count; i++ {
		sheet := x.workBook.GetSheet(i)
		if sheetName == sheet.Name {
			return sheet, nil
		}
	}
	errInfo := fmt.Sprintf("指定的sheet[%s]不存在！", sheetName)
	return nil, errors.New(errInfo)
}
